package com.ruoyi.lvlian.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.lvlian.domain.BusinessLicenseInfo;
import com.ruoyi.lvlian.domain.InvoiceInfo;
import com.ruoyi.lvlian.dto.PaymentInfoDto;
import com.ruoyi.lvlian.service.ICommonService;
import com.ruoyi.lvlian.service.InvoiceInfoService;
import com.ruoyi.lvlian.vo.PaymentInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.lvlian.domain.PaymentInfo;
import com.ruoyi.lvlian.service.IPaymentInfoService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 支付信息Controller
 *
 * @author liyuxi
 * @date 2024-05-13
 */
@Api(value = "支付信息相关", tags = "支付单信息相关接口")
@RestController
@RequestMapping("/paymentInfo")
public class PaymentInfoController extends BaseController {
    @Autowired
    private IPaymentInfoService paymentInfoService;

    @Autowired
    private ICommonService iCommonService;
    //@RequiresPermissions("lvlian:paymentInfo:list")
    @GetMapping("/list")
    public TableDataInfo list(PaymentInfoDto paymentInfo) {
        if (SecurityUtils.getUserId() == 1) {
            paymentInfo.setOrgCodes(new ArrayList<>(Arrays.asList("50000000")));
        } else {
            List<String> orgCodes = iCommonService.queryCurrentOrgCode(SecurityUtils.getUserId());
            if(orgCodes.size()==0){
                return getDataTable(new ArrayList<PaymentInfoVo>() )  ;
            }
            if (Objects.isNull(paymentInfo.getOrgCodes()) || paymentInfo.getOrgCodes().isEmpty()) {
                orgCodes.removeIf(code -> code.length() != 8);
                paymentInfo.setOrgCodes( orgCodes);
            }

        }
        
        startPage();

        List<PaymentInfoVo> list = paymentInfoService.selectPaymentInfoList(paymentInfo);
        return getDataTable(list);
    }


    /**
     * 查询支付信息列表
     */
    @ApiOperation("查询支付关联发票单信息列表,带剩余金额")
    @GetMapping("/queryPaymentInfoInvioceList")
    public R<TableDataInfo> queryPaymentInfoInvioceList(PaymentInfoDto paymentInfo) {// 包含完税id、orgCode
        startPage();
        if (StringUtils.isEmpty(paymentInfo.getOrgCode())) {
            return R.fail(400, "公司编码不能为空");
        }
        List<PaymentInfoVo> list = paymentInfoService.queryPaymentInfoInvioceList(paymentInfo);
        return R.ok(getDataTable(list));
    }




//    /**
//     * 导出支付信息列表
//     */
//    //@RequiresPermissions("lvlian:paymentInfo:export")
//    @Log(title = "支付信息", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, PaymentInfoDto paymentInfo) {
//        List<PaymentInfo> list = paymentInfoService.selectPaymentInfoList(paymentInfo);
//        ExcelUtil<PaymentInfo> util = new ExcelUtil<PaymentInfo>(PaymentInfo.class);
//        util.exportExcel(response, list, "支付信息数据");
//    }

    /**
     *
     */
    @ApiOperation("获取支付信息详细信息 getInfoById")
    //@RequiresPermissions("lvlian:paymentInfo:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(paymentInfoService.selectPaymentInfoById(id));
    }


    @ApiOperation("获取支付信息详细信息 getInfoById")
    @GetMapping("/getInfoById")
    public AjaxResult getInfoById(@ApiParam(value = "获取支付信息详细信息", required = true) @RequestParam(value = "id") String id) {
        return success(paymentInfoService.selectPaymentInfoById(id));
    }

    /**
     * 新增支付信息
     */
/*    //@RequiresPermissions("lvlian:paymentInfo:add")
    @Log(title = "支付信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PaymentInfo paymentInfo) {
        return toAjax(paymentInfoService.insertPaymentInfo(paymentInfo));
    }*/
    private String validateInData(PaymentInfo paymentInfo) {
        if (StringUtils.isEmpty(paymentInfo.getPaymentNum())  ) {
            return "支付单号不能为空";
        }
        return "success";
    }
    //@RequiresPermissions("lvlian:paymentInfo:edit")
    @Log(title = "支付信息", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改支付信息")
    public AjaxResult edit(@RequestBody@Validated PaymentInfo paymentInfo) {
        if (!"success".equalsIgnoreCase(validateInData(paymentInfo))) {
            return error(validateInData(paymentInfo));
        }
        return toAjax(paymentInfoService.updatePaymentInfo(paymentInfo));
    }

    /**
     * 删除支付信息
     */


    @PostMapping("/remove")
    public AjaxResult remove(@RequestBody String[] ids) {
        return toAjax(paymentInfoService.deletePaymentInfoByIds(ids));
    }
    @ApiOperation("导入采购付款信息")
    @PostMapping("/importInfoBuyer")
    public AjaxResult importInfo(MultipartFile file) {
        // 获取到批量导入的数据集合
        List<PaymentInfo> dtoList = null;
        try {
            dtoList = paymentInfoService.importInfo( file ,"采购付款信息", 3);
        } catch (Exception e) {
            return success("模板错误");
        }
        for(PaymentInfo po: dtoList   ){
            po.setCategory( "采购付款信息");
            po.setPaymentType("付款回单");
        }
        int totalSussess = paymentInfoService.bachSave(dtoList);
        int total = dtoList.size();
        int totalFail = total - totalSussess;
        String msg = "解析到" + total + "条数据，" + "导入成功" + totalSussess + "条，导入失败" + totalFail + "条！";
        return success(msg);
    }

    @ApiOperation("导入销售收款信息")
    @PostMapping("/importInfoSeller")
    public AjaxResult importInfoSeller(MultipartFile file) {
        // 获取到批量导入的数据集合
        List<PaymentInfo> dtoList = null;
        List<PaymentInfo> newList = new ArrayList<>();
        try {
            dtoList = paymentInfoService.importInfo( file ,"销售收款信息", 3);
            for(PaymentInfo po: dtoList   ){
                po.setCategory( "销售收款信息");
                po.setPaymentType( "收款回单");
                newList.add(po);
            }


            int totalSussess = paymentInfoService.bachSave(newList);
            int total = dtoList.size();
            int totalFail = total - totalSussess;
            String msg = "解析到" + total + "条数据，" + "导入成功" + totalSussess + "条，导入失败" + totalFail + "条！";
            return success(msg);
        } catch (Exception e) {
            e.printStackTrace();
            return success("模板错误");
        }



    }
    @GetMapping("/queryPaymentInfoAgg")
    @ApiOperation("财务看板")
    public AjaxResult queryInvoiceInfoAgg(@ApiParam(value = "采购/销售", required = true) @RequestParam(value = "category") String category,
                                          @ApiParam(value = "发票号码", required = true) @RequestParam(value = "invoiceNum") String invoiceNum
    ) {
        return success(paymentInfoService.queryPaymentInfoAgg(category, invoiceNum ));
    }
}
